package com.seaboxdata.threadHandler;

import com.alibaba.fastjson.JSONObject;
import com.seaboxdata.entity.DistrictStatus;
import com.seaboxdata.kafka.BaseStringKafkaConsumer;
import com.seaboxdata.service.DistrictStatusService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * @author
 * @create 2020-11-10 10:47
 **/
@Component
@Slf4j
public class DistrictStatusHandler implements DisposableBean, Runnable {

    private Thread thread;

    @Autowired
    private DistrictStatusService districtStatusService;

    @Autowired
    private BaseStringKafkaConsumer baseStringKafkaConsumer;

    @Value("${real.trans.districtStatusTopic}")
    private String topic;

    @Value("${interface.isTest}")
    private String isTest;

    private boolean flag;

    @Autowired
    public void initThread() {
        if("true".equals(isTest)){
            return;
        }
        this.flag = true;
        this.thread = new Thread(this);
        thread.setName("districtStatusThread");
        this.thread.start();
        log.info("districtStatusThread start");
    }

    @Override
    public void run() {
        KafkaConsumer<String, String> consumer = baseStringKafkaConsumer.getConsumer(topic);
        while (flag) {
            ConsumerRecords<String, String> messages = consumer.poll(Duration.ofMillis(100L));
            List<DistrictStatus> results = new ArrayList<>();
            for (ConsumerRecord<String, String> message : messages) {
                results.add(JSONObject.parseObject(message.value(), DistrictStatus.class));
            }

            //写入数据库
            if (!CollectionUtils.isEmpty(results)) {
                try{
                    districtStatusService.saveBatch(results);
                    consumer.commitSync();
                }catch (Exception e){
                    log.error("write districtStatus to database error");
                    e.printStackTrace();
                }

            }
        }
    }

    @Override
    public void destroy() throws Exception {
        this.flag = false;
    }
}
